package com.dragon.web.ykd.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.dragon.app.commons.constant.ContactsTypeEnum;
import com.dragon.app.commons.dto.AcApplyEnvironmentinfoDTO;
import com.dragon.app.commons.dto.JiaYinJinKApplyLoanDTO;
import com.dragon.app.commons.dto.ProductApplyDTO;
import com.dragon.app.ykd.dto.AcLoanApplyNode;
import com.dragon.app.ykd.dto.AcLoanInfoDTO;
import com.dragon.app.ykd.dto.LoanExtensionRecoreds;
import com.dragon.app.ykd.dto.SaveLinkmansDTO;
import com.dragon.app.ykd.dto.UserDataDTO;
import com.dragon.app.ykd.service.ClientAppService;
import com.dragon.loan.entity.AcApplyEnvironmentInfo;
import com.dragon.loan.repository.AcLoanApplyInfoRepository;
import com.dragon.web.commons.utils.UserUtils;
import com.fintech.common.constant.ErrorCode;
import com.fintech.common.enums.ReturnCode;
import com.fintech.common.vo.FintechResult;
import com.fintech.user.entity.User;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.loanapply.dto.MclaLoanApplyLinkmanDTO;

@Controller
@RequestMapping("${platform.name.code}")
public class ClientAppController {
	@Autowired
	private ClientAppService clientAppService;
	
	@Autowired
	AcLoanApplyInfoRepository acLoanApplyInfoRepository;
	
	/**
	 * 验证是否有正在进件的工单
	 * 
	 * @param shortUrl
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/verify")
	public FintechResult loanVerify(@RequestHeader String accessToken, @RequestHeader String idFintechUmUser, HttpServletRequest request) {
		return clientAppService.loanVerify(accessToken, idFintechUmUser);
	}
	
	/**
	 * 客户app第一次进件 立即申请<br>
	 * 只用于线上产品申请
	 * @param shortUrl
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "apply/loan")
	public FintechResult applyLoan(@RequestBody ProductApplyDTO productApplyDTO, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser, HttpServletRequest request) {
	    MarvelsLogUtil.getInstance().info("==================客户app第一次进件 立即申请==================,参数:" +JSON.toJSONString(productApplyDTO));
		
	    AcApplyEnvironmentInfo acApplyEnvironmentinfo = AcApplyEnvironmentinfoDTO.getAcApplyEnvironmentinfo(request, productApplyDTO);
		MarvelsLogUtil.getInstance().info("客户端信息:" +JSON.toJSONString(productApplyDTO));
		
		return clientAppService.applyLoan(productApplyDTO,acApplyEnvironmentinfo, accessToken, idFintechUmUser);
	}
	
	/**
	 * 复贷申请
	 * 
	 * @param productApplyDTO
	 * @param accessToken
	 * @param idFintechUmUser
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "apply/reloan")
	public FintechResult applyReLoan(@RequestBody ProductApplyDTO productApplyDTO, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser, HttpServletRequest request) {
		MarvelsLogUtil.getInstance().info("==================复贷申请信息==================");
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		AcApplyEnvironmentInfo acApplyEnvironmentinfo = AcApplyEnvironmentinfoDTO.getAcApplyEnvironmentinfo(request,
				productApplyDTO);
		MarvelsLogUtil.getInstance().info("客户端信息:" + JSON.toJSONString(productApplyDTO));

		return clientAppService.applyReLoan(productApplyDTO, acApplyEnvironmentinfo, accessToken, idFintechUmUser);
	}
	
	
	/**
	 * 复贷申请
	 * 
	 * @param productApplyDTO
	 * @param accessToken
	 * @param idFintechUmUser
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "apply/v2/reloan")
	public FintechResult applyV2ReLoan(@RequestBody ProductApplyDTO productApplyDTO, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser, HttpServletRequest request) {
		MarvelsLogUtil.getInstance().info("==================v2复贷申请信息==================");
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		AcApplyEnvironmentInfo acApplyEnvironmentinfo = AcApplyEnvironmentinfoDTO.getAcApplyEnvironmentinfo(request,
				productApplyDTO);
		MarvelsLogUtil.getInstance().info("v2客户端信息:" + JSON.toJSONString(productApplyDTO));

		return clientAppService.applyV2ReLoan(productApplyDTO, acApplyEnvironmentinfo, accessToken, idFintechUmUser);
	}
	
	/**
	 * 获取紧急联系人类型列表
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "relation/getTypeList")
	public FintechResult getRelationTypeList(@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", ContactsTypeEnum.getContactsNameList());
	}
	
	/**
	 * 保存紧急联系人
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "relation/save")
	public FintechResult saveRelation(@RequestBody List<MclaLoanApplyLinkmanDTO> loanApplyLinkmanList,
		@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("=====relation/save=====,接受参数 ="+JSON.toJSONString(loanApplyLinkmanList));
		if(loanApplyLinkmanList == null || loanApplyLinkmanList.isEmpty() || loanApplyLinkmanList.size() < 2){
			return FintechResult.getResult(ErrorCode.FAIL, "请填写完成", null);
		}
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
		}
		return clientAppService.saveRelation(loanApplyLinkmanList, user.getId());
	}
	
	/**
	 * 保存用户对应的联系人信息
	 * 
	 * @param acLinkmanMobiles
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "save/saveLinkmans")
	public FintechResult saveLinkmans(@RequestBody List<SaveLinkmansDTO> acLinkmanMobiles,
			@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("=====save/linkmans=====,接受参数:acLinkmanMobiles="+JSON.toJSONString(acLinkmanMobiles));
		if (acLinkmanMobiles == null || acLinkmanMobiles.isEmpty()) {
			return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", null);
		}
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
		}
		return clientAppService.saveLinkmans(acLinkmanMobiles, user.getId());
	}
	
	/**
	 * 保存用户对应的联系人、工作地址、居住地址
	 * 
	 * @param acLinkmanMobiles
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "save/contactInfo")
	public FintechResult saveContactInfo(@RequestBody UserDataDTO userData,
			@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("=====save/contactInfo=====,接受参数:userData="+JSON.toJSONString(userData));
		if (userData == null) {
			return FintechResult.getResult(ErrorCode.FAIL, "居住信息、工作信息、婚姻信息不可为空", null);
		}
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
		}
		return clientAppService.saveContactInfo(userData, user.getId());
	}	
	
	/**
	 * 查询最新的节点信息
	 * 
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/queryLastApplyNode")
	public FintechResult queryLastApplyNode(@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================查询最新的节点信息==================");
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.queryLastApplyNode(user.getId());
	}
	
	@ResponseBody
	@RequestMapping(value = "loan/queryAllApplyeList")
	public FintechResult queryAllApplyeList(@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================查询最新的节点信息==================");
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.queryAllApplyeList(user.getId(),"");
	}	

	@ResponseBody
	@RequestMapping(value = "loan/queryAllRepaymentApply")
	public FintechResult queryAllRepaymentApply(@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("loan/queryAllRepaymentApply 查询所有待还款的申请列表");
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.queryAllApplyeList(user.getId(),LoanStateConstant.D01.toString());
	}	
	
	/**
	 * 添加节点流程信息（该方法暂时不启用）
	 * 
	 * @param acLoanApplyNode
	 *            {loanId--贷款编号, nodeCode--节点编码（0.进件初始化节点 1.通讯录已授权 2.运营商已认证 3.支付宝已认证 4.审核中 5.审核通过 6.审核拒绝 7.确认借款）}
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/addLoanApplyNode")
	public FintechResult addLoanApplyNode(@RequestBody AcLoanApplyNode acLoanApplyNode, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================添加节点流程信息==================,参数:" + acLoanApplyNode);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.addLoanApplyNode(acLoanApplyNode);
	}
	
	/**
	 * 添加通讯录认证成功节点流程信息（通讯录数据都获取成功后再调用）
	 * 
	 * @param loanId--贷款编号
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/addLinkManAuthNode/{loanId}")
	public FintechResult addCommunicationVerifyNode(@PathVariable String loanId, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================添加节点流程信息==================,参数:" + loanId);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.addLinkManAuthNode(loanId);
	}
	
	/**
	 * 添加通讯录认证成功节点流程信息（通讯录数据都获取成功后再调用）
	 * 
	 * @param loanId--贷款编号
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/v2/addLinkManAuthNode/{loanId}")
	public FintechResult addCommunicationVerifyNodeV2(@PathVariable String loanId, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================v2添加节点流程信息==================,参数:" + loanId);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.addLinkManAuthNodeV2(loanId, accessToken, idFintechUmUser);
	}
	
	/**
	 * 魔蝎TASKID回调
	 * 
	 * @param map
	 *            {taskId--魔蝎任务ID,loanId--贷款编号,mobile--手机号码,type--魔蝎类型（1.运营商
	 *            2.公积金 3.支付宝）}
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "callback/mxTask")
	public FintechResult callBackMxTask(@RequestBody Map<String, String> map) {
		MarvelsLogUtil.getInstance().info("==================魔蝎TASKID回调==================,参数:" + JSON.toJSONString(map));
		return clientAppService.callBackMxTask(map);
	}
	
	/**
	 * 前端触发审核
	 * 
	 * @param loanId--贷款编号
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/doApprove/{loanId}")
	public FintechResult doApprove(@PathVariable String loanId, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================前端触发审核==================,参数:" + loanId);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.doApprove(loanId);
	}
	
	/**
	 * 确认贷款详情页面
	 * 
	 * @param loanId--贷款编号
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/queryLoanApplyInfo/{loanId}")
	public FintechResult queryLoanApplyInfo(@PathVariable String loanId, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================确认贷款详情页面==================,loanId=" + loanId);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.queryLoanApplyInfo(loanId);
	}
	
	/**
	 * 确认贷款数据是否完整（绑卡、签合同）
	 * 
	 * @param loanId--贷款编号
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/confirmLoanDataFull/{loanId}")
	public FintechResult confirmLoanDataFull(@PathVariable String loanId, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================确认贷款数据是否完整（绑卡、签合同）==================,loanId=" + loanId);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.confirmLoanDataFull(loanId);
	}
	
	/**
	 * 展示合同信息
	 * 
	 * @param loanId--贷款编号
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/showContract/{loanId}")
	public FintechResult showContract(@PathVariable String loanId, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================展示合同信息==================,参数:" + loanId);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.showContract(loanId);
	}
	
	@ResponseBody
	@RequestMapping(value = "loan/queryProductType")
	public FintechResult queryProductType() {
		MarvelsLogUtil.getInstance().info("==================查询线上产品==================");
		return clientAppService.queryProductType();
	}
	
	@ResponseBody
	@RequestMapping(value="loanSuccessList")
	public FintechResult loanSuccessList(){	
		return FintechResult.getSuccessResult(acLoanApplyInfoRepository.loanSuccessList());
	}
	
//	@ResponseBody
//	@RequestMapping(value="deviceInfo")
//	public FintechResult deviceInfo(@RequestBody EdcDeviceDto deviceDto){	
//		creditReportService.save(deviceDto);
//		return FintechResult.getSuccessResult(null);
//	}
	
	/**
	 * 展期确认操作
	 * 
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/confirmLoanExtension")
	public FintechResult confirmLoanExtension(@RequestBody LoanExtensionRecoreds loanExtensionRecoreds, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================确认展期信息==================,参数:" + loanExtensionRecoreds);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.confirmLoanExtension(loanExtensionRecoreds);
	}
	
	/**
	 * 根据LOANID查询展期数据（倒序）
	 * 
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/loanExtensionQuery/{loanId}")
	public FintechResult loanExtensionQuery(@PathVariable String loanId, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================展期数据查询信息==================,参数:" + loanId);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.queryLoanExtensionByLoanId(loanId);
	}
	
	
	/**
	 * 确认贷款申请
	 * 
	 * @param loanId--贷款编号
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/confirmLoanApply/{loanId}")
	public FintechResult confirmLoanApply(@PathVariable String loanId, @RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("==================确认贷款申请==================,loanId=" + loanId);
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		return clientAppService.confirmLoanApply(loanId,user);
	}
	
	/**
	 * 获取借款合同列表
	 * @param accessToken
	 * @param idFintechUmUser
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "loan/contractContent")
	public FintechResult contractContent(@RequestBody AcLoanInfoDTO loanInfo,@RequestHeader String accessToken,
			@RequestHeader String idFintechUmUser) {
		MarvelsLogUtil.getInstance().info("contractContent,loanId=" + loanInfo.getLoanId());
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}else if(StringUtils.isBlank(loanInfo.getLoanId())) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "申请单号不存在");
		}
		return clientAppService.contractContent(loanInfo.getLoanId());
	}
	
}
